package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.conmmon.R;
import com.itheima.domain.User;
import com.itheima.utils.ValidateCodeUtils;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author liwanhu
 * @datetime 2021/10/30 11:06
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> code(@RequestBody User user, HttpSession session) {
        log.info(user.toString());
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)) {
            //随机生成4位数验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
            /*SMSUtils.sendMessage("生活记录","SMS_209163022","17616529949",code.toString());*/
            //将验证码存到redis中
            redisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
            //将获取的随机验证码存入session域中
            //session.setAttribute(phone, code);
            return R.success("手机号验证码短信发送成功");
        }
        return R.success("成功");
    }

    /**
     * 手机用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //在redis中获取验证码
        Object sessionCode = redisTemplate.opsForValue().get(phone);
        //获取session中的验证码
        //Object sessionCode = session.getAttribute(phone);
        //进行验证码的比对
        if (sessionCode != null && sessionCode.equals(code)) {
            //对比成功的话说明登录成功
            QueryWrapper<User> qw = new QueryWrapper<>();
            //判断登录的手机号是否在user表中存在
            qw.eq("phone", phone);
            //获取对象
            User user = userService.getOne(qw);
            if (user == null) {
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setStatus(1);
                user.setPhone(phone);
                userService.save(user);
            }
            //将登录对象id存入session中
            session.setAttribute("user", user.getId());
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 实战第一天
     * 用户端,退出登录
     *
     * @return
     */
    @PostMapping("loginout")
    public R<String> loginOut(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.success("成功退出");
    }
}
